package com.zhen.aikan.util;

import cn.hutool.core.collection.CollectionUtil;
import com.zhen.aikan.entity.Scheduled;
import com.zhen.aikan.entity.VodDetail;
import com.zhen.aikan.service.IVodDetailService;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * @author LiJiaZhen
 * @date 2023/9/16 22:25
 */

@Component("task")
@Slf4j
public class Task {
    @Autowired
    private IVodDetailService vodDetailService;
    protected final Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * 获取最近24小时更新的视频
     */
    @Transactional(rollbackFor = Exception.class)
    public void getUpdatedVod(String url) {
        logger.info("执行 getUpdatedVod，当前时间：{}，任务参数：{}", LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")), url);
//        String url = "https://collect.wolongzy.cc/api.php/provide/vod/?ac=detail&h=24&pg=";
        for (int i = 1; ; i++) {
            List<VodDetail> vodDetails = Spider.crawlVideo(url + i);
            if (CollectionUtil.isEmpty(vodDetails)) {
                logger.info("====================更新完成=====================");
                return;
            }
            vodDetailService.saveOrUpdateBatch(vodDetails);
        }
    }


    /**
     * 更新所有资源
     *
     * @param url
     */
    @Transactional(rollbackFor = Exception.class)
    public void updatedAllVod(String url) {
        logger.info("执行 updatedAllVod，当前时间：{}，任务参数：{}", LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")), url);
        for (int i = 1; ; i++) {
            // 添加阻塞操作
            try {
                logger.info("====================第{}页完成=====================",i);
                Thread.sleep(10000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            List<VodDetail> vodDetails = Spider.crawlVideo(url + i);
            if (CollectionUtil.isEmpty(vodDetails)) {
                logger.info("====================更新完成=====================");
                return;
            }
            vodDetailService.saveOrUpdateBatch(vodDetails);
        }
    }
}
